package cn.shyouchi.wuguanjia.android.widget.dialog;

import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;


public class CongratulationDialogFragment extends DialogFragment {

    @BindView(R.id.congratulation_dialog_second)
    TextView secondTextView;

    public interface CongratulationDialogListener {
        void onCongratulationDialogPositiveClick(DialogFragment dialog);

        void onCongratulationDialogTimeUp(DialogFragment dialog);
    }

    CongratulationDialogListener mListener;


    public void setonClickListener( CongratulationDialogListener mListener) {
        this.mListener = mListener;
    }

    int seconds = 3;
    Timer timer;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
           getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    seconds -= 1;
                    if (seconds == 0) {
                        timer.cancel();

                        getActivity().finish();
                        if (mListener != null) {

                            mListener.onCongratulationDialogTimeUp(CongratulationDialogFragment.this);
                        }
                    } else {
                        secondTextView.setText(seconds + "");
                    }
                }
            });
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_fragment_congratulation, container, false);
        ButterKnife.bind(this, view);
        timer = new Timer();
        timer.schedule(task, 1000, 1000);
        return view;
    }

    @OnClick(R.id.congratulation_dialog_confirm_button)
    void onConfirmButtonTapped() {
        if (timer != null) {
            timer.cancel();
        }

        if (mListener != null) {
            mListener.onCongratulationDialogPositiveClick(this);
        }

    }
}
